package modules.fin.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import luxing.common.controller.BaseController;
import luxing.exception.BusinessException;
import luxing.hibernate.CriteriaQuery;
import luxing.util.CriteriaQueryUtil;
import luxing.util.LoginUserUtil;
import luxing.util.ValidatorUtil;
import luxing.web.model.DataGrid;
import luxing.web.model.Result;
import modules.fin.entity.Expenses;
import modules.fin.entity.IncomeUnit;
import modules.fin.entity.IncomeUnitSum;
import modules.fin.service.ExpensesService;
import modules.fin.service.IncomeUnitService;
import modules.sys.entity.Dict;
import modules.sys.entity.Log;
import modules.sys.service.DictService;
import modules.sys.service.LogService;

/**
 * 
 * @author zzc
 *
 */
@Controller
@RequestMapping("/incomeUnitController")
public class IncomeUnitController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(IncomeUnitController.class);

	@Autowired
	private LogService logService;
	@Autowired
	private IncomeUnitService incomeUnitService;
	@Autowired
	private ExpensesService expensesService;
	@Autowired
	private DictService dictService;

	/**
	 * 列表页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "index")
	public ModelAndView index(HttpServletRequest request) {
		List<Expenses> expensesList = expensesService.listByTypeAndStatus(Expenses.TYPE_INCOME_UNIT,
				Expenses.STATUS_ENABLE);
		request.setAttribute("expensesList", expensesList);
		return new ModelAndView("modules/fin/incomeUnit-list");
	}

	/**
	 * 列表数据
	 * 
	 * @param incomeUnit
	 * @param request
	 * @param response
	 * @param dataGrid
	 */
	@RequestMapping(params = "list")
	public void list(IncomeUnit incomeUnit, HttpServletRequest request, HttpServletResponse response,
			DataGrid dataGrid) {
		try {
			CriteriaQuery cq = new CriteriaQuery(IncomeUnit.class, dataGrid);
			CriteriaQueryUtil.assembling(cq, incomeUnit, request.getParameterMap());
			// 费用类型
			String exs = request.getParameter("exs");
			if (StringUtils.isNotBlank(exs)) {
				cq.eq("expenses.id", exs);
			}
			cq.add();
			incomeUnitService.listByPage(cq, true);
			dataGrid.setFooter("amount,vehicle.sn:合计");
			listView(response, dataGrid);
		} catch (Exception e) {
			logger.error("收单位款查询失败", e);
			throw new BusinessException("收单位款查询失败", e);
		}
	}

	/**
	 * 增加页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(HttpServletRequest req) {
		List<Expenses> expensesList = expensesService.listByTypeAndStatus(Expenses.TYPE_INCOME_UNIT,
				Expenses.STATUS_ENABLE);
		req.setAttribute("expensesList", expensesList);
		return new ModelAndView("modules/fin/incomeUnit-add");
	}

	/**
	 * 修改页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goUpdate(IncomeUnit incomeUnit, HttpServletRequest req) {
		if (StringUtils.isNotBlank(incomeUnit.getId())) {
			incomeUnit = incomeUnitService.get(IncomeUnit.class, incomeUnit.getId());
			req.setAttribute("incomeUnitPage", incomeUnit);
			List<Expenses> expensesList = expensesService.listByTypeAndStatus(Expenses.TYPE_INCOME_UNIT,
					Expenses.STATUS_ENABLE);
			req.setAttribute("expensesList", expensesList);
		}
		return new ModelAndView("modules/fin/incomeUnit-update");
	}

	/**
	 * 往来单位核销页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "goUnitSettle")
	public ModelAndView goUnitSettle(HttpServletRequest req) {
		List<Expenses> expensesList = expensesService.listByTypeAndStatus(Expenses.TYPE_INCOME_UNIT,
				Expenses.STATUS_ENABLE);
		req.setAttribute("expensesList", expensesList);
		return new ModelAndView("modules/fin/incomeUnit-settle");
	}

	/**
	 * 车辆核销页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "goVehicleSettle")
	public ModelAndView goVehicleSettle(IncomeUnit incomeUnit, HttpServletRequest req) {
		if (StringUtils.isNotBlank(incomeUnit.getId())) {
			incomeUnit = incomeUnitService.get(IncomeUnit.class, incomeUnit.getId());
			req.setAttribute("incomeUnitPage", incomeUnit);
			List<Expenses> expensesList = expensesService.listByTypeAndStatus(Expenses.TYPE_INCOME_UNIT,
					Expenses.STATUS_ENABLE);
			req.setAttribute("expensesList", expensesList);
		}
		return new ModelAndView("modules/fin/incomeUnitVehicle-settle");
	}

	/**
	 * 查看页面
	 * 
	 * @param incomeUnit
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "goDetail")
	public ModelAndView goDetail(IncomeUnit incomeUnit, HttpServletRequest request) {
		if (StringUtils.isNotBlank(incomeUnit.getId())) {
			incomeUnit = incomeUnitService.get(IncomeUnit.class, incomeUnit.getId());
			request.setAttribute("incomeUnitPage", incomeUnit);
			List<Expenses> expensesList = expensesService.listByTypeAndStatus(Expenses.TYPE_INCOME_UNIT,
					Expenses.STATUS_ENABLE);
			request.setAttribute("expensesList", expensesList);
		}
		return new ModelAndView("modules/fin/incomeUnit-detail");
	}

	/**
	 * 车辆明细tab
	 * 
	 * @return
	 */
	@RequestMapping(params = "tab")
	public ModelAndView tab(HttpServletRequest req) {
		return new ModelAndView("modules/fin/incomeUnit-tab");
	}

	/**
	 * 往来单位核销明细
	 * 
	 * @return
	 */
	@RequestMapping(params = "unitSettleTab")
	public ModelAndView unitSettleTab(HttpServletRequest req) {
		// 获取往来单位
		String unit = req.getParameter("unit");
		if (StringUtils.isBlank(unit)) {
			List<Dict> dictList = dictService.listByGroupCode("unit", LoginUserUtil.getLoginUser().getTenantId());
			if (CollectionUtils.isNotEmpty(dictList)) {
				unit = dictList.get(0).getId();
			}
		}
		// 获取费用
		String expensesId = req.getParameter("expensesId");
		if (StringUtils.isBlank(expensesId)) {
			List<Expenses> expensesList = expensesService.listByTypeAndStatus(Expenses.TYPE_INCOME_UNIT,
					Expenses.STATUS_ENABLE);
			if (CollectionUtils.isNotEmpty(expensesList)) {
				expensesId = expensesList.get(0).getId();
			}
		}
		List<IncomeUnit> incomeUnitList = incomeUnitService.listByUnitAndExpensesAndStatus(unit, expensesId,
				IncomeUnit.STATUS_NO);
		BigDecimal totalAmount = new BigDecimal(0);
		for (IncomeUnit incomeUnit : incomeUnitList) {
			totalAmount = totalAmount.add(incomeUnit.getAmount());
		}
		req.setAttribute("totalAmount", totalAmount);
		req.setAttribute("incomeUnitList", incomeUnitList);
		return new ModelAndView("modules/fin/incomeUnitSettle-tab");
	}

	/**
	 * 新增
	 * 
	 * @param incomeUnit
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public Result doAdd(IncomeUnit incomeUnit, HttpServletRequest request) {
		String msg = null;
		try {
			if (CollectionUtils.isNotEmpty(incomeUnit.getIncomeUnitList())) {
				for (IncomeUnit entity : incomeUnit.getIncomeUnitList()) {
					entity.setUnit(incomeUnit.getUnit());
					entity.setExpenses(incomeUnit.getExpenses());
					entity.setStatus(IncomeUnit.STATUS_NO);
				}
				incomeUnitService.batchSave(incomeUnit.getIncomeUnitList());
			}
			msg = "收单位款登记成功";
			logger.info(msg);
			logService.addLogInfo(msg, Log.OPERATE_ADD);
		} catch (Exception e) {
			msg = "收单位款登记失败";
			logger.error(msg, e);
			throw new BusinessException(msg, e);
		}
		return Result.success(msg);
	}

	/**
	 * 修改
	 * 
	 * @param incomeUnit
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public Result doUpdate(IncomeUnit incomeUnit, HttpServletRequest request) {
		String msg = null;
		try {
			incomeUnitService.saveOrUpdate(incomeUnit);
			msg = "收单位款修改成功";
			logger.info(msg);
			logService.addLogInfo(msg, Log.OPERATE_UPDATE);
		} catch (Exception e) {
			msg = "收单位款修改失败";
			logger.error(msg, e);
			throw new BusinessException(msg, e);
		}
		return Result.success(msg);
	}

	/**
	 * 删除
	 * 
	 * @return
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public Result doDel(IncomeUnit incomeUnit, HttpServletRequest request) {
		String msg = null;
		try {
			incomeUnit = incomeUnitService.get(IncomeUnit.class, incomeUnit.getId());
			incomeUnitService.delete(incomeUnit);
			msg = "收单位款删除成功";
			logger.info(msg);
			logService.addLogInfo(msg, Log.OPERATE_DEL);
		} catch (Exception e) {
			msg = "收单位款删除失败";
			logger.error(msg, e);
			throw new BusinessException(msg, e);
		}
		return Result.success(msg);
	}

	/**
	 * 往来单位核销
	 * 
	 * @param incomeUnitSum
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "doUnitSettle")
	@ResponseBody
	public Result doUnitSettle(IncomeUnitSum incomeUnitSum, HttpServletRequest request) {
		String msg = null;
		try {
			if (CollectionUtils.isNotEmpty(incomeUnitSum.getIncomeUnitList())) {
				// 编号
				String sn = incomeUnitService.getSn();
				incomeUnitSum.setSn(sn);
				// 状态
				incomeUnitSum.setStatus(IncomeUnitSum.STATUS_ENABLE);
				// 核销金额
				BigDecimal totalAmount = new BigDecimal(0);
				Iterator<IncomeUnit> iterator = incomeUnitSum.getIncomeUnitList().iterator();
				while (iterator.hasNext()) {
					IncomeUnit incomeUnit = iterator.next();
					if (StringUtils.equals(incomeUnit.getStatus(), IncomeUnit.STATUS_YES)) {
						totalAmount = totalAmount.add(incomeUnit.getAmount());
						incomeUnitSum.setExpenses(incomeUnit.getExpenses());
						incomeUnit.setSettleBy(LoginUserUtil.getUser().getName());
						incomeUnit.setSettleDate(new Date());
					} else {
						iterator.remove();
					}
				}
				incomeUnitSum.setAmount(totalAmount);
				// bean校验
				msg = ValidatorUtil.validate(incomeUnitSum);
				if (StringUtils.isNotBlank(msg)) {
					return Result.error(msg);
				}
				incomeUnitService.settle(incomeUnitSum);
				msg = "收单位款核销成功";
				logger.info(msg);
				logService.addLogInfo(msg, Log.OPERATE_ADD);
			}
		} catch (Exception e) {
			msg = "收单位款核销失败";
			logger.error(msg, e);
			throw new BusinessException(msg, e);
		}
		return Result.success(msg);
	}

	/**
	 * 车辆核销
	 * 
	 * @param incomeUnit
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "doVehicleSettle")
	@ResponseBody
	public Result doVehicleSettle(IncomeUnit incomeUnit, HttpServletRequest request) {
		String msg = null;
		try {
			List<IncomeUnit> incomeUnitList = new ArrayList<IncomeUnit>();
			incomeUnit.setStatus(IncomeUnit.STATUS_YES);
			incomeUnit.setCreateBy(LoginUserUtil.getUser().getName());
			incomeUnit.setCreateDate(new Date());
			incomeUnitList.add(incomeUnit);
			// 收款记录
			IncomeUnitSum incomeUnitSum = new IncomeUnitSum();
			String sn = incomeUnitService.getSn();
			incomeUnitSum.setSn(sn);
			incomeUnitSum.setUnit(incomeUnit.getUnit());
			incomeUnitSum.setExpenses(incomeUnit.getExpenses());
			incomeUnitSum.setAmount(incomeUnit.getAmount());
			String way = request.getParameter("way");
			incomeUnitSum.setWay(way);
			incomeUnitSum.setStatus(IncomeUnitSum.STATUS_ENABLE);
			incomeUnitSum.setIncomeUnitList(incomeUnitList);

			incomeUnitService.settle(incomeUnitSum);
			msg = "收单位款核销成功";
			logger.info(msg);
			logService.addLogInfo(msg, Log.OPERATE_UPDATE);
		} catch (Exception e) {
			msg = "收单位款核销失败";
			logger.error(msg, e);
			throw new BusinessException(msg, e);
		}
		return Result.success(msg);
	}

}
